import React, { useState, useEffect } from 'react'
import { Col, Form, Input, Button, Card, Table, Select, DatePicker, Radio, Row, Pagination   } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { formLayout } from '@/utils/utils'
import RenderButtom from '@/components/RenderButton'
import { fetchBrandRptTotal, fetchStoresList, fetchBrandsList, fetchBrandRptList, exportExcel } from '@/services/dataCenter/financeData'
import SearchBox from '@/components/SearchBox'
const {RangePicker} = DatePicker
import moment from 'moment'
import styles from '../dataCenter.less'

const BrandStatistics = props => {
  const { form } = props
  const { getFieldDecorator } = form
  const [brandRptList, setBrandRptList] = useState([])
  const [total, setTotalPage] = useState(0)
  const [dateFormat, setDateFormat] = useState('YYYY-MM-DD')
  const [storesList, setStoresList] = useState([])
  const [brandsList, setBrandsList] = useState([])
  const [totalInfo, setTotalInfo] = useState({})
  const [pageInfo, setPageInfo] = useState({})
  const [param, setParam] = useState({pageNo: 1, pageSize: 99999,})

  const formParam = {
    pageSize: 10,
    pageNo: 1,
    startTime: moment().format('YYYY-MM-DD'),
    endTime: moment().format('YYYY-MM-DD'),
    queryType: 'day'
  }

  useEffect(() => {
    init()
    _fetchStoresList()
    _fetchBrandsList()
    _fetchBrandRptTotal()
  }, [])

  const init = async (formParam) => {
    console.log(formParam)
    const r_1 = await fetchBrandRptList(formParam)
    if (r_1.code == 0 && r_1.data) {
      setBrandRptList(r_1.data)
      setTotalPage(r_1.total)
      setPageInfo({
        pageTurnoverTotalMoney: r_1.pageTurnoverTotalMoney,
        pageTotalDiscountFee: r_1.pageTotalDiscountFee,
        pageDiscountFee: r_1.pageDiscountFee,
        pageDeductionFee: r_1.pageDeductionFee,
        pageFee: r_1.pageFee,
        pageSettlementMoney: r_1.pageSettlementMoney
      })
    }
  }
  const _fetchBrandRptTotal = async () => {
    let param = {
      pageNo: 1,
      pageSize: 10,
      startTime: null,
      endTime: null,
      queryType: 'day',
      supplierId: 1072,
      storeId: 2063,
      // storeType:
    }
    const res = await fetchBrandRptTotal(param)
    if (res.code == 0) {
      setTotalInfo(res.data)
    }
  }
  const _fetchBrandsList = async (param) => {
    const res = await fetchBrandsList(param)
    setBrandsList(res.data)
  }
  const _fetchStoresList = async () => {
    let param = {
      supplierId: 1072,
      pageSize: 99999
    }
    const res = await fetchStoresList(param)
    setStoresList(res.data)
  }

  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }

  // 按钮处理
  const handleBtn = type => {
    switch (type) {
      case 97:
        // ...导出Excel
        break;
      default:
        break;
    }
  }
  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log(dateFormat)
      init({
        ...values,
        startTime: values.selectedTime ? values.selectedTime[0].format(dateFormat) : null,
        endTime: values.selectedTime ? values.selectedTime[1].format(dateFormat) : null,
      })
    })
  }
  const handlePageChange = (page) => {
    init({
      ...param,
      pageNo: page,
    })
  }
  const handleChangeType =(e) => {
    let val = e.target.value
    switch (val) {
      case 'day':
        setDateFormat('YYYY-MM-DD')
        break;
      case 'month':
        setDateFormat('YYYY-MM')
        break;
      case 'quarter':
        setDateFormat('YYYY')
        break;
      case 'year':
        setDateFormat('YYYY')
        break;
      default:
        break;
    }
  }
  // 查询条件
  const getFields = () => {
    return (<>
      <Col span={8}>
        <Form.Item label="选择门店" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator('storeId', {})
            (<Select>
              {storesList && storesList.map(m => <Select.Option key={m.id} value={m.id}>{m.name}</Select.Option>)}
            </Select>
          )}
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="品牌名称" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator('brandName', {})
            (<Input />)}
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="选择品牌" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator('brandId', {})
            (<Select>
              {brandsList && brandsList.map(m => <Select.Option key={m.id} value={m.id}>{m.nameCn}</Select.Option>)}
            </Select>
          )}
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="商品名称" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator('goodsName', {})
            (<Input />)}
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label={`筛选时间`} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator(`selectedTime`, {
            initialValue: [moment(), moment()],
          })
            (<RangePicker format={dateFormat} />)}
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label={`日期阶段`} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator(`queryType`, {initialValue: 'day'})
            (<Radio.Group buttonStyle="solid" onChange={handleChangeType}>
              <Radio.Button value="day">日</Radio.Button>
              <Radio.Button value="month">月</Radio.Button>
              <Radio.Button value="quarter">季度</Radio.Button>
              <Radio.Button value="year">年</Radio.Button>
            </Radio.Group>)}
        </Form.Item>
      </Col>
    </>)
  }
  const showTotal = (total) => {
    return `共 ${total} 条`
  }
  return (<PageHeaderWrapper>
    <Card>
      <Form layout={formLayout}>
        <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      </Form>
    </Card>
    <Card style={{marginTop: '10px'}}>
      <RenderButtom click={handleBtn} />
      <table width="100%" border="1" cellSpacing="0" cellPadding="10">
        <thead>
          <tr>
            <th rowSpan="2">序号</th>
            <th rowSpan="2">时间</th>
            <th rowSpan="2">门店</th>
            <th rowSpan="2">品牌</th>
            <th rowSpan="2">品名</th>
            <th rowSpan="2">总销量</th>
            <th colSpan="6">交易金额（总）</th>
            <th colSpan="3">应扣应收（总）</th>
            <th rowSpan="2">退款（总）</th>
            <th rowSpan="2">应结算（总）</th>
          </tr>
          <tr>
            <th>微信</th>
            <th>支付宝</th>
            <th>银行卡</th>
            <th>现金</th>
            <th>其他</th>
            <th>总额</th>
            <th>支付手续费</th>
            <th>品牌扣点</th>
            <th>扣点手续费</th>
          </tr>
        </thead>
        <tbody>
        {brandRptList.length && brandRptList.map((item, index) =>
          <tr key={index}>
            <td>{index+1}</td>
            <td>{item.queryDate}</td>
            <td>{item.storeName}</td>
            <td>{item.brandName}</td>
            <td>{item.goodsName}</td>
            <td>{item.totalSales}</td>
            <td>{item.wxpMoney}</td>
            <td>{item.alpMoney}</td>
            <td>{item.bankMoney}</td>
            <td>{item.cashMoney}</td>
            <td>{item.otherMoney}</td>
            <td>{item.totalMoney}</td>
            <td>{item.totalDiscountFee}</td>
            <td>{item.deductionFee}</td>
            <td>{item.discountFee}</td>
            <td>{item.refundMoney}</td>
            <td>{item.settlemetnAmount}</td>
          </tr>)}
        </tbody>
      </table>
      <Pagination style={{float: 'right', margin: '10px'}} showTotal={showTotal} defaultCurrent={1} total={parseInt(total)} onChange={handlePageChange} />
      <ul className={styles.ulTongji}>
        <li>
          <span>总 计：</span>
          <span>总支付：{totalInfo.totalPaymoney} </span>
          <span>总交易：¥{totalInfo.turnoverTotalMoney}</span>
          <span>总支付手续费：¥{totalInfo.totalDiscountFeeMoney}</span>
          <span>费率总扣：¥{totalInfo.totalDiscountMOney}</span>
          <span>扣点总扣：¥{totalInfo.totalDeductionMoney}</span>
          <span>总扣费：¥{totalInfo.totalFee}</span>
          <span>总结算：¥{totalInfo.totalSettlementMoney}</span>
        </li>
        <li>
          <span>页小计：</span>
          <span>总交易：¥{pageInfo.pageTurnoverTotalMoney} </span>
          <span>总支付手续费： ¥{pageInfo.pageTotalDiscountFee}</span>
          <span>费率总扣：¥{pageInfo.pageDiscountFee} </span>
          <span>扣点总扣：¥{pageInfo.pageDeductionFee} </span>
          <span>扣费：¥{pageInfo.pageFee}</span>
          <span>结算：¥{pageInfo.pageSettlementMoney}</span>
        </li>
      </ul>
    </Card>
  </PageHeaderWrapper>)
}

export default Form.create()(BrandStatistics)
